<script setup lang="ts">
import { ref, computed, onMounted, onUnmounted, reactive } from 'vue'
import { Editor, RowFlex, ElementType, ControlType } from '@hufe921/canvas-editor'
import { useRouter, useRoute } from 'vue-router';
import baseCard from '@/components/base-card/index.vue'
import {
    DocumentOnePage20Regular, DocumentPageBreak20Regular,
    Subtract16Filled, Add16Filled, DocumentPageTopCenter24Regular,
    FullScreenMaximize16Regular, FullScreenMinimize24Regular, Settings24Regular,
    DocumentMargins24Regular, ArrowUndo48Regular, ArrowRedo48Filled, PaintBrush24Regular, Eraser24Regular,
    TextUnderline24Regular, TextItalic24Regular, TextBold24Filled, FontDecrease24Regular, FontIncrease24Regular,
    TextStrikethrough24Filled, TextSuperscript24Regular, TextSubscript24Regular, TextColor24Filled,
    TextCaseTitle24Regular, TextNumberListLtr24Regular, ArrowAutofitContent24Regular, TextColumnOne24Regular,
    TableSwitch24Regular, Image24Regular, Link24Regular, DataWaterfall24Regular, Code24Regular, DocumentPageBreak24Regular,
    ControlButton24Regular, CheckboxChecked24Regular, RadioButton24Filled, Timer24Regular, Search24Regular, Print24Filled, TextColorAccent24Filled,
    TextAlignJustify24Regular, TextAlignLeft24Regular, TextAlignRight24Regular, TextAlignCenter24Regular, TextAlignDistributedEvenly24Regular
} from '@vicons/fluent'
import canvasTableHead from '@/components/canvas-table/index.vue';
import { sseService } from "@/assets/utils/sse";
import type { SSEChatParams } from "@/assets/utils/sse";
import { setUrlParams } from "@/service/sseUrl";
import { FORM_ADD } from '../../service/apis/from';

const router = useRouter()
const route = useRoute()
// const sx: any = route.query.sx
// const sx: any = route.query.sx
// const str = decodeURIComponent(qd)
// const qdArr = JSON.parse(str)
const queryData = ref(route.query)
// queryData.value = sx
// console.log('jkdsjdsjkdsjkdsjkdsjkdsdsjkdsjk', qd);


const canvasEditor = ref<any>(null)
const wordRef = ref<any>(null)
const wordCarfRef = ref<any>(null)
const wordContentRef = ref<any>(null)
const active = ref(false)
const active1 = ref(true)
const placement = ref()


const placementRightTitle = ref('文本编辑')

const canvasEditorForm = reactive(
    {
        title: '',
        word: [],
    }
)

const muluList = ref<any>([
    { id: 1, name: '主诉:', pos: 'left' },
    { id: 2, name: '现病史:', pos: 'right' },
    { id: 3, name: '既往史:', pos: 'bottom' },
    { id: 1, name: '流行病史:', pos: 'left' },
    { id: 1, name: '体格检查', pos: 'right' },
    { id: 1, name: '辅助检查:', pos: 'right' },
    { id: 1, name: '处置治疗::', pos: 'right' },
    { id: 1, name: '门诊诊断:', pos: 'right' },
    { id: 1, name: '电子签名:', pos: 'right' },
    { id: 1, name: '其他记录:', pos: 'right' },
])

const popselectValue = ref()
const fontSizeValue = ref()
const options = [
    {
        label: 'A4',
        value: 'A4'
    },
    {
        label: 'A3',
        value: 'A3'
    },
    {
        label: 'A2',
        value: 'A2',
        //   disabled: true
    },
    {
        label: 'A1',
        value: 'A1'
    },
    {
        label: '5号信封',
        value: '5号信封'
    },
    {
        label: '6号信封',
        value: '6号信封'
    },
    {
        label: '7号信封',
        value: '7号信封',
        //   disabled: true
    },
    {
        label: '9号信封',
        value: '9号信封'
    },
    {
        label: '法律用纸',
        value: '法律用纸'
    },
    {
        label: '信纸',
        value: '信纸'
    },
]
const options1 = [
    {
        label: '纵向',
        value: '纵向'
    },
    {
        label: '横向',
        value: '横向'
    },

]
const fontList = [
    { label: '微软雅黑', value: '微软雅黑', style: "font-family:'Microsoft YaHei';" },
    { label: '华文宋体', value: '华文宋体', style: "font-family:'华文宋体';" },
    { label: '华文黑体', value: '华文黑体', style: "font-family:'华文黑体';" },
    { label: '华文仿宋', value: '华文仿宋', style: "font-family:'华文仿宋';" },
    { label: '华文楷体', value: '华文楷体', style: "font-family:'华文楷体';" },
    { label: '华文琥珀', value: '华文琥珀', style: "font-family:'华文琥珀';" },
    { label: '华文楷体', value: '华文楷体', style: "font-family:'华文楷体';" },
    { label: '华文隶书', value: '华文隶书', style: "font-family:'华文隶书';" },
    { label: '华文新魏', value: '华文新魏', style: "font-family:'华文新魏';" },
    { label: '华文行楷', value: '华文行楷', style: "font-family:'华文行楷';" },
    { label: '华文中宋', value: '华文中宋', style: "font-family:'华文中宋';" },
    { label: '华文彩云', value: '华文彩云', style: "font-family:'华文彩云';" },
    { label: 'Arial', value: 'Arial', style: "font-family:'Arial';" },
    { label: 'Segoe ul', value: 'Segoe ul', style: "font-family:'Segoe UI';" },
    { label: 'Ink Free', value: 'Ink Free', style: "font-family:'Ink Free';" },
    { label: 'Fantasy', value: 'Fantasy', style: "font-family:'Fantasy';" },

]

const fontSizeList = [
    { label: '初号', value: '初号', size: '56' },
    { label: '小初', value: '小初', size: '48' },
    { label: '一号', value: '一号', size: '34' },
    { label: '小一', value: '小一', size: '32' },
    { label: '二号', value: '二号', size: '29' },
    { label: '小二', value: '小二', size: '24' },
    { label: '三号', value: '三号', size: '21' },
    { label: '小三', value: '小三', size: '20' },
    { label: '四号', value: '四号', size: '18' },
    { label: '小四', value: '小四', size: '16' },
    { label: '五号', value: '五号', size: '14' },
    { label: '小五', value: '小五', size: '12' },
    { label: '六号', value: '六号', size: '10' },
    { label: '小六', value: '小六', size: '8' },
    { label: '七号', value: '七号', size: '7' },
    { label: '八号', value: '八号', size: '6' },

]


onMounted(() => {
    // console.log(wordContentRef.value, wordContentRef.value.offsetHeight);

    // boxHeight.value = wordContentRef.value.offsetHeight
    active1.value = true
    active.value = true
    placement.value = 'right'
    canvasEditor.value = new Editor(wordRef.value, {
        header: [
            {
                value: '山东发达面粉集团',
                size: 32,
                color: '#FF0000',
                rowFlex: RowFlex.JUSTIFY
            },
            {
                value: '\n',
                type: ElementType.SEPARATOR
            }
        ],
        main: [],
        footer: [
            {
                value: '\n',
                type: ElementType.SEPARATOR
            },
            {
                value: '集团地址：山东省济南市西城大厦10F',
                size: 18
            }
        ]
    }, {})
    sseServiceOpen()
    // console.log(queryData.value);

})
onUnmounted(() => {
    sseService.disconnect()
})

//see 链接
function sseServiceOpen() {
    let sx: any = queryData.value.sx
    const onopen = () => {
        console.log("word数据sse连接成功")
    }
    // 建立连接
    let sseChatParams: SSEChatParams = {
        onopen,
        url: setUrlParams(sx, 'readme'),
        onmessage: (event: MessageEvent) => {
            // 收到消息
            console.log('模板', event.data);
            // let fst = event.data.replace(/\\n/g, "\n")
            // let strArr = fst.split(';')
            // let strArr1 = strArr[1].split('\n')
            // const ddf = Papa.parse(fst, { header: true, delimiter: ";", newline: "\n" })
            let fst1 = event.data
            let wo = JSON.parse(fst1)
            console.log(wo['数据结构']);

            canvasEditor.value.command.executeSetHTML(wo['数据结构'])



        },
        finallyHandler: () => {
            console.log("finallyHandler操作")
        }
    };
    sseService.connect(sseChatParams)


}


function saveData(params: any) {
    console.log(params);
    canvasEditorForm.title = params
}

function middleClick(params: any) {
    if (params.pos != 'null') {
        placementRightTitle.value = params.name
        active.value = true
        placement.value = params.pos
    }
    if (params.name == '表格') {
        canvasEditor.value.command.executeInsertTable(2, 3)

    }
    // if (params.name == '控件') {

    //     console.log(params);

    // }
    if (params.name == '保存') {
        let data = {
            类型: "数据",
            内容: {
                应用名称: queryData.value.name ? queryData.value.name : '',
                名称: canvasEditorForm.title,
                内容: canvasEditor.value.command.getHTML()
            }
        }

        console.log('vvvvvvvv', data, canvasEditor.value.command.getValue());

        FORM_ADD({ "params": JSON.stringify(data) }).then((res: any) => {
            console.log('结果', res);
            if (res.stacode == 200) {
            }
        }).catch((err: any) => {
            // console.log('err', err);
            // loading.value = false
        })
    }

}



function endClick(params: any) {
    placementRightTitle.value = '文本编辑'
    active.value = true
    placement.value = params
}


function handleSelect(params: any) {
    // console.log(params);
    if (params == '1') {
        canvasEditor.value?.command.executeInsertControl({
            type: ElementType.CONTROL,
            value: '',
            control: {
                conceptId: '2',
                type: ControlType.SELECT,
                value: null,
                code: null,
                placeholder: '有无',
                prefix: '{',
                postfix: '}',
                valueSets: [
                    {
                        value: '有',
                        code: '98175'
                    },
                    {
                        value: '无',
                        code: '98176'
                    },
                    {
                        value: '不详',
                        code: '98177'
                    }
                ]
            }
        })
    }
    if (params == '2') {

        canvasEditor.value.command.executeInsertControl({
            type: ElementType.CONTROL,
            value: '',
            control: {
                conceptId: '2',
                type: ControlType.SELECT,
                value: null,
                code: null,
                placeholder: '有无',
                prefix: '{',
                postfix: '}',
                valueSets: [
                    {
                        value: '有',
                        code: '98175'
                    },
                    {
                        value: '无',
                        code: '98176'
                    },
                    {
                        value: '不详',
                        code: '98177'
                    }
                ]
            }
        })

    }
    if (params == '3') {
        console.log('时间');
        let time = new Date().toLocaleString();
        canvasEditor.value.command.executeInsertElementList([{
            type: ElementType.CONTROL,
            value: time,
        }])
    }
}

function popselectFontSet(val: any) {
    console.log(val);
    canvasEditor.value.command.executeFont(val)

    fontList.forEach(el => {

        if (el.value == val) {
            console.log(el);
            canvasEditor.value.command.executeSize(el.style)
        }
    })
}
function popselectSizeSet(val: any) {
    fontSizeList.forEach(el => {
        if (el.value == val) {
            canvasEditor.value.command.executeSize(el.size)
        }
    })

}



function fontSizeUndo() {
    canvasEditor.value.command.executeUndo()
}
function fontSizeAdd() {
    canvasEditor.value.command.executeSizeAdd()
}
function fontSizeMinus() {
    canvasEditor.value.command.executeSizeMinus()
}

function fontSizeUnderline() {
    canvasEditor.value.command.executeUnderline()
}
function fontSizeItalic() {
    canvasEditor.value.command.executeItalic()
}
function fontSizeBold() {
    canvasEditor.value.command.executeBold()
}
</script>
<template>
    <baseCard ref="wordCarfRef" id="wordCarfRef" :head-show="true" style=" overflow: hidden;">
        <template #headers>
            <div style="width: 100%;">
                <canvasTableHead v-on:save-data="saveData" v-on:middle-click="middleClick" v-on:end-click="endClick"
                    v-on:handle-select="handleSelect" />
            </div>
        </template>


        <div class="word-content wordlay"  id="wordPRef">
            <div ref="wordRef" id="wordRef" class="canvas-editor"></div>
        </div>


        <n-drawer v-model:show="active" :width="200" :height="placement == 'bottom' ? 50 : 200"
            style="line-height: 50px;" :placement="placement" :trap-focus="false" :block-scroll="false"
            :show-mask="false" :mask-closable="false" to="#wordPRef">
            <n-drawer-content title="目录" v-if="placement == 'left'" closable>
                <div v-for="(j, k) in muluList" :key="k">
                    <span>{{ j.name }}</span>
                </div>
            </n-drawer-content>
            <n-drawer-content :title="placementRightTitle" v-if="placement == 'right'" closable>
                <div v-if="placementRightTitle == '文本编辑'">
                    <!-- <n-icon size="20">
                        <ArrowUndo48Regular @click ="fontSizeUndo"/>
                    </n-icon>
                    <n-icon size="20">
                        <ArrowRedo48Filled @click ="fontSizeUndo"/>
                    </n-icon> -->
                    <n-icon size="20" title="格式刷(双击可连续使用)">
                        <PaintBrush24Regular />
                    </n-icon>
                    <n-icon size="20" title="清除格式">
                        <Eraser24Regular />
                    </n-icon>
                    <div style="height: 1px;background-color: #000;"></div>
                    <n-select v-model:value="popselectValue" size="small" :options="fontList" placeholder="选择字体"
                        @update:value="popselectFontSet" />
                    <n-select v-model:value="fontSizeValue" size="small" :options="fontSizeList" placeholder="选择字体大小"
                        @update:value="popselectSizeSet" />
                    <div style="height: 1px;background-color: #000;margin-top: 10px;"></div>
                    <n-icon size="20">
                        <FontIncrease24Regular @click="fontSizeAdd" />
                    </n-icon>
                    <n-icon size="20">
                        <FontDecrease24Regular @click="fontSizeMinus" />
                    </n-icon>

                    <n-icon size="20">
                        <TextUnderline24Regular @click="fontSizeUnderline" />
                    </n-icon>
                    <n-icon size="20">
                        <TextItalic24Regular @click="fontSizeItalic" />
                    </n-icon>
                    <n-icon size="20">
                        <TextBold24Filled @click="fontSizeBold" />
                    </n-icon>
                    <n-icon size="20">
                        <TextStrikethrough24Filled />
                    </n-icon>
                    <n-icon size="20">
                        <TextSuperscript24Regular />
                    </n-icon>
                    <n-icon size="20">
                        <TextSubscript24Regular />
                    </n-icon>
                    <n-icon size="20" title="高亮">
                        <TextColorAccent24Filled />
                    </n-icon>
                    <n-icon size="20" title="字体颜色">
                        <TextColor24Filled />
                    </n-icon>
                    <!-- <n-icon size="20">
                    <input type="color" id="color" style="height: 10px;width: 25px;"  title="文字颜色"/>
                </n-icon>
                <n-icon size="20">
                    <input type="color" id="color" style="height: 10px;width: 25px;"  title="文字颜色"/>
                </n-icon> -->
                    <!-- <input type="color" id="highlight"> -->
                    <div style="height: 1px;background-color: #000;"></div>
                    <n-icon size="20">
                        <TextAlignLeft24Regular />
                    </n-icon>
                    <n-icon size="20">
                        <TextAlignJustify24Regular />
                    </n-icon>
                    <n-icon size="20">
                        <TextAlignRight24Regular />
                    </n-icon>
                    <n-icon size="20">
                        <TextAlignCenter24Regular />
                    </n-icon>
                    <n-icon size="20">
                        <TextAlignDistributedEvenly24Regular />
                    </n-icon>
                    <n-icon size="20">
                        <TextNumberListLtr24Regular />
                    </n-icon>
                    <div style="height: 1px;background-color: #000;"></div>
                    <n-icon size="20">
                        <TableSwitch24Regular />
                    </n-icon>
                    <n-icon size="20">
                        <Image24Regular />
                    </n-icon>
                    <n-icon size="20">
                        <Link24Regular />
                    </n-icon>
                    <n-icon size="20">
                        <DataWaterfall24Regular />
                    </n-icon>
                    <n-icon size="20">
                        <DocumentPageBreak24Regular />
                    </n-icon>
                    <n-icon size="20">
                        <CheckboxChecked24Regular />
                    </n-icon>
                    <n-icon size="20">
                        <RadioButton24Filled />
                    </n-icon>
                    <n-icon size="20">
                        <Code24Regular />
                    </n-icon>
                    <n-icon size="20">
                        <Timer24Regular />
                    </n-icon>
                    <div style="height: 1px;background-color: #000;"></div>
                    <n-icon size="20">
                        <Search24Regular />
                    </n-icon>
                    <n-icon size="20">
                        <Print24Filled />
                    </n-icon>
                </div>
            </n-drawer-content>
            <n-drawer-content v-if="placement == 'bottom'">
                <div style="display: flex;justify-content: space-between; align-items: center;height: 17px">
                    <span style="display: flex; align-items: center;">
                        <n-icon size="20">
                            <DocumentOnePage20Regular />
                        </n-icon>
                        <span>可见页码：<span class="page-no-list">1</span></span>
                        <span>页面：<span class="page-no">1</span>/<span class="page-size">1</span></span>
                        <span>字数：<span class="word-count">0</span></span>
                    </span>

                    <span class="editor-mode" style="" title="编辑模式(编辑、清洁、只读、表单、设计)">编辑模式</span>
                    <span style="display: flex; align-items: center;">
                        <n-icon size="20">
                            <Subtract16Filled />
                        </n-icon>
                        <span class="page-scale-percentage" title="显示比例(点击可复原Ctrl+0)">100%</span>
                        <n-icon size="20">
                            <Add16Filled />
                        </n-icon>
                        <n-popselect v-model:value="popselectValue" :options="options" trigger="click">
                            <n-icon size="20">
                                <DocumentPageTopCenter24Regular />
                            </n-icon>
                        </n-popselect>
                        <n-popselect v-model:value="popselectValue" :options="options1" trigger="click">
                            <n-icon size="20">
                                <DocumentPageTopCenter24Regular />
                            </n-icon>
                        </n-popselect>
                        <!-- <n-icon size="20"> -->
                        <!-- <FullScreenMaximize16Regular /> -->
                        <!-- <FullScreenMinimize24Regular /> -->
                        <!-- </n-icon> -->
                        <n-icon size="20">
                            <DocumentMargins24Regular />
                        </n-icon>
                        <n-icon size="20">
                            <Settings24Regular />
                        </n-icon>
                    </span>
                </div>
            </n-drawer-content>
        </n-drawer>
    </baseCard>

</template>
<style src="./index.scss" scoped></style>
